package com.dotflat.safe.service.impl;

import com.dotflat.rest.PO.AreableObjectBasePO;
import com.dotflat.rest.service.impl.AreableObjectBaseServiceImpl;
import com.dotflat.safe.domain.SterilizationTarget;
import com.dotflat.safe.repository.SterilizationTargetRepository;
import com.dotflat.safe.service.SterilizationTargetService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageImpl;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;

import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;
import java.util.*;


@Service
public class SterilizationTargetServiceImpl extends AreableObjectBaseServiceImpl<SterilizationTarget, SterilizationTargetRepository>
        implements SterilizationTargetService {

    @Autowired
    @Override
    public void setBaseRepository(SterilizationTargetRepository repository){
        super.setBaseRepository(repository);
    }

    @Override
    public Page<SterilizationTarget> page(String areaId, String staffId, AreableObjectBasePO param, PageRequest pageRequest) {

        Page<SterilizationTarget> page = super.page(areaId, staffId, param, pageRequest);

        if (page.getContent().size() == 0){

            AreableObjectBasePO po = new AreableObjectBasePO();
            po.setId(areaId);
            po.setAreaId(areaId);

            //创建园区默认对象
            Specification<SterilizationTarget> specification = new Specification<SterilizationTarget>() {
                @Override
                public Predicate toPredicate(Root<SterilizationTarget> root, CriteriaQuery<?> query, CriteriaBuilder criteriaBuilder) {
                    List<Predicate> predicates = new ArrayList<>();

                    generatePagePredicates(root, query, criteriaBuilder, po, predicates);

                    query.where(predicates.toArray(new Predicate[predicates.size()]));
                    return query.getRestriction();
                }
            };

            Optional<SterilizationTarget> op = baseRepository.findOne(specification);

            if (op.isPresent()){
                page = new PageImpl<>(Arrays.asList(op.get()));
            } else {

                SterilizationTarget result = new SterilizationTarget();

                result.setId(areaId);
                result.setAreaId(areaId);
                result.setCreatedBy(staffId);
                result.setCreated(new Date());
                result.setTitle("消毒柜");
                result.setRemark("系统生成的默认消毒目标");

                baseRepository.save(result);

                page = new PageImpl<>(Arrays.asList(result));
            }


        }

        return page;
    }
}